package org.ttitfly.ttcore.mybatis;

public class MySQLDialect extends Dialect {

    public boolean supportsLimit() {
        return true;
    }

    public boolean supportsLimitOffset() {
        return true;
    }

    public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
        sql = sql.trim();
        boolean isForUpdate = false;
        if (sql.toLowerCase().endsWith(" for update")) {
            sql = sql.substring(0, sql.length() - 11);
            isForUpdate = true;
        }

        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
//        if (offset > 0) {
//            pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
//        } else {
//            pagingSelect.append("select * from ( ");
//        }
        pagingSelect.append(sql);
        if (offset > 0) {
            int begin = (offset-1)*limit+1;
            pagingSelect.append(" limit "+ begin + ","+limitPlaceholder);
        } else {
            pagingSelect.append(" limit "+ offsetPlaceholder+"," + limitPlaceholder);
        }

        if (isForUpdate) {
            pagingSelect.append(" for update");
        }

        return pagingSelect.toString();
    }
    


}
